package com.shujia.Zookeeper;

import org.apache.zookeeper.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;

public class Demo01ZKAPI {
    ZooKeeper zk;

    @Before
    public void init() throws IOException {
        zk = new ZooKeeper("master:2181,node1:2181,node2:2181", 20000, null);

    }

    // 创建一个ZNode
    @Test
    public void createZNode() throws InterruptedException, KeeperException {
        /**
         * CreateMode:
         *  PERSISTENT 永久保存
         *  EPHEMERAL  在连接断开的时候会自动将创建的ZNode删除
         */
        zk.create(
                "/test",
                "10".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.PERSISTENT
        );
    }

    // 创建一个临时的ZNode
    @Test
    public void createEPHEMERALZNode() throws InterruptedException, KeeperException {
        /**
         * CreateMode:
         *  PERSISTENT 永久保存
         *  EPHEMERAL  在连接断开的时候会自动将创建的ZNode删除
         */
        zk.create(
                "/test1",
                "20".getBytes(),
                ZooDefs.Ids.OPEN_ACL_UNSAFE,
                CreateMode.EPHEMERAL
        );

        while (true) {
            // 避免zk连接自动关闭
        }
    }

    // 获取指定的ZNode上的值
    @Test
    public void getData() throws InterruptedException, KeeperException {
        byte[] data = zk.getData("/test", null, null);
        System.out.println(new String(data));
    }

    // 修改指定ZNode的值
    @Test
    public void setData() throws InterruptedException, KeeperException {
        zk.setData("/test", "11".getBytes(), -1);
    }

    // 删除指定ZNode
    @Test
    public void deleteZNode() throws InterruptedException, KeeperException {
        zk.delete("/test", -1);
    }

    // 观察者
    @Test
    public void setWatcher() throws InterruptedException, KeeperException {
        // 判断指定的ZNode存不存在，并且可以指定一个Watcher
        zk.exists("/test", new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println(event.getPath());
                System.out.println(event.getState());
                System.out.println(event.getWrapper());
                System.out.println(event.getType());
                System.out.println("捕捉到了ZNode的变化，触发了事件");
            }
        });

        while(true){
            // 避免ZK连接自动断开
        }
    }


    @After
    public void close() throws InterruptedException {
        zk.close();
    }

}
